package cn.itcast.search.service.impl;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.dto.common.PageDTO;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.item.SearchItemDTO;
import cn.itcast.hmall.dto.search.SearchReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.item.ItemDoc;
import cn.itcast.search.service.SearchService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearcherServiceImpl implements SearchService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 导入es数据
     *
     * @return
     */
    @Override
    public ResultDTO importItemData() {
        try {
            SearchItemDTO searchItemDTO = new SearchItemDTO();
            Integer page = 1, size =500;
            searchItemDTO.setSize(size);
            searchItemDTO.setPage(page);

            //分页查询商品
            PageDTO<Item> itemPageDTO = itemClient.queryItemByPage(searchItemDTO);
            //查询总条数
            int total = itemPageDTO.getTotal().intValue();

            for (; page * size < total + size; page++) {
                searchItemDTO.setPage(page);
                List<Item> list = itemClient.queryItemByPage(searchItemDTO).getList();
                //创建request请求
                BulkRequest request = new BulkRequest();


                //遍历item对象
                for (Item item : list) {
                    //将Item转换为ItemDoc
                    ItemDoc itemDoc = new ItemDoc(item);
                    //批量导入文档
                    request.add(new IndexRequest("item")
                            .id(itemDoc.getId()+"")
                            .source(JSON.toJSONString(itemDoc), XContentType.JSON));
                }
                //发送请求
                client.bulk(request, RequestOptions.DEFAULT);
            }
            return ResultDTO.ok();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
      }

    /**
     * 自动补全
     * @param key
     * @return
     */
    @Override
    public List<String> suggestion(String key) {

        try {
            //准备请求
            SearchRequest request = new SearchRequest("item");

            //请求参数
            request.source()
                    .suggest(new SuggestBuilder().addSuggestion("mySuggestion",
                            SuggestBuilders
                                    .completionSuggestion("suggestion")
                                    .prefix(key)
                                    .skipDuplicates(true)
                                    .size(10)));

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //解析数据
            Suggest suggest = response.getSuggest();
            //根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("mySuggestion");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 过滤聚合
     * @param searchReqDTO
     * @return
     */
    @Override
    public Map<String,List<String>> filters(SearchReqDTO searchReqDTO) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.query
            SearchSourceBuilder source = request.source();
            bulidBasicQuery(searchReqDTO,source);
            // 2.2.设置size
            source.size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据分类名称，获取分类结果
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);
            // 4.2.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildAggregation(SearchRequest request) {
        //分类聚合
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(50)
        );
        //品牌聚合
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(50)
        );
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
           list.add(key);
        }
        return list;
    }

    /**
     * 分页查询
     * @param searchReqDTO
     * @return
     */
    @Override
    public PageDTO<ItemDoc> list(SearchReqDTO searchReqDTO) {

        try {
            //创建request请求
            SearchRequest request = new SearchRequest("item");
            //搜索条件
            SearchSourceBuilder source = request.source();
            bulidBasicQuery(searchReqDTO,source);

            //设置分页
            Integer page = searchReqDTO.getPage();
            Integer size = searchReqDTO.getSize();
            source.from((page-1)*size).size(size);

            //sortBy排序
            if (StringUtils.isNotBlank(searchReqDTO.getSortBy())){
                //销量降序
                if (searchReqDTO.getSortBy().equals("sold")){
                    source.sort("sold",SortOrder.DESC);
                    //价格升序
                }else if (searchReqDTO.getSortBy().equals("price")){
                    source.sort("price",SortOrder.ASC);
                }
            }
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应数据
            SearchHits hits = response.getHits();
            //查询总条数
            long total = hits.getTotalHits().value;
            //遍历hits
            ArrayList<ItemDoc> itemDocs = new ArrayList<>();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);

                itemDoc.setPrice(itemDoc.getPrice()*100);

                //获取高亮处理结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)){
                    HighlightField field = highlightFields.get("name");
                    //高亮处理结果字符串
                    String highLightResult = StringUtils.join(field.getFragments());
                    itemDoc.setName(highLightResult);
                }
                itemDocs.add(itemDoc);
            }
            return new PageDTO<>(total,itemDocs);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 构建基础查询条件
     * @param searchReqDTO  请求参数
     * @param source  条件
     */
    private void bulidBasicQuery(SearchReqDTO searchReqDTO, SearchSourceBuilder source) {

        //构建bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索
        if(StringUtils.isBlank(searchReqDTO.getKey())) {
            //key为空 查询全部
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else{
            boolQuery.must(QueryBuilders.matchQuery("all",searchReqDTO.getKey()));
            source.highlighter(new HighlightBuilder().field("name").requireFieldMatch(false)
                    .preTags("<em>")
                    .postTags("</em>"));
        }

        //分类过滤查询
        if (StringUtils.isNotBlank(searchReqDTO.getCategory())){
            boolQuery.filter(QueryBuilders.termQuery("category",searchReqDTO.getCategory()));
        }
        //品牌过滤查询
        if (StringUtils.isNotBlank(searchReqDTO.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",searchReqDTO.getBrand()));
        }
        //价格过滤查询
        if (searchReqDTO.getMaxPrice()!=null && searchReqDTO.getMinPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(searchReqDTO.getMinPrice())
                    .lte(searchReqDTO.getMaxPrice()));
        }

        //算分函数条件
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(boolQuery, //原始查询条件
                        //算分函数 数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                //算分函数
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        //筛选条件
                                        QueryBuilders.termQuery("isAD",true),
                                        //计算方法
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        }).boostMode(CombineFunction.MULTIPLY);  //加权模式

        //放行source
        source.query(functionScoreQueryBuilder);
    }

    //下架商品从索引库中删除商品
    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //上架商品添加商品到索引库
    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询商品
            Item item = itemClient.queryItemById(id);
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("item").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
